package com.muyan.netty.aiosocket;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * 此处仅作客户端演示回调，实际业务设计中，可以嵌套多样化的回调<br>
 * eg. 编写 WriteHandler ReadHandler 实现 CompletionHandler
 * @author zzl
 */
public class ClientCompletionHandler implements CompletionHandler<Void, Void> {

    private AsynchronousSocketChannel socketChannel;

    public ClientCompletionHandler(AsynchronousSocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void completed(final Void result, final Void attachment) {
        System.out.println("成功连接到服务器!");
        try {
            // 给服务器发送信息并等待发送完成
            socketChannel.write(ByteBuffer.wrap("From client:Hello i am client".getBytes())).get();
            ByteBuffer readBuffer = ByteBuffer.allocate(128);
            // 阻塞等待接收服务端数据
            socketChannel.read(readBuffer).get();
            System.out.println(new String(readBuffer.array()));
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed(final Throwable exc, final Void attachment) {
        exc.printStackTrace();
    }
}
